import xbmc
import xbmcgui
import urllib, urllib2
import os, sys, re

__cwd__      = sys.modules[ "__main__" ].__cwd__
__settings__ = sys.modules[ "__main__" ].__settings__
__htm__      = sys.modules[ "__main__" ].__htm__
__test__     = sys.modules[ "__main__" ].__test__

class GUI(xbmcgui.WindowXML):
	def __init__(self, *args, **kwargs):
		xbmcgui.WindowXMLDialog.__init__(self, *args, **kwargs)
		self.keyword = kwargs['keyword']
		print 'Search keyword : [%s]' % self.keyword
		self.label = 'Rezultate pentru "' + self.keyword + '"'
		self.doModal()

	def onInit(self):
		self.testmode = __settings__.getSetting('testmode')
		self.page_number = '1'
		self.page = ''
		self.action_cancel_dialog = (9, 10)
		self.list = self.getControl(82)
		self.page_list = self.getControl(83)
		self.list.reset()
		self.page_list.reset()
		self.getControl(81).setLabel(self.label + ' :' )
		if __test__:
			__htm__.getPage(url=__cwd__ + '\\samples\\search.htm', txdata=None)
		else:
			__htm__.getPage(url='http://www.vplay.ro/serials/?s=' + self.keyword + '&page=1', txdata=None)
		self.page = __htm__.Page
		self.getControl(57).setImage(__htm__.UserAvatar)
		self.getControl(58).setLabel(__htm__.UserID)
		self.getControl(59).setLabel(__htm__.UserDays + ' zile VIP')
		self.RefreshItems()
		self.RefreshPages()

	def onClick(self, controlId):
		# print 'Control ID : [%s]' % str(controlId)
		if controlId == 9002:
			print 'Favorites'
			import resources.lib.Fav as Fav
			page_fav = Fav.GUI("vplay_fav.xml", __cwd__, "default")
			# self.close()
		elif controlId == 9003:
			import resources.lib.GenreList as GenreList
			page_genre_list = GenreList.GUI("vplay_genre_list.xml", __cwd__, "default")
			
		elif controlId == 9004:
			print 'Search'
		elif controlId == 9005:
			print 'Login'
			__settings__.openSettings()
		elif controlId == 82:
			item = self.list.getSelectedItem()
			# =================================================================================================
			# PLAY the item!
			if (self.testmode != 'true'):
				import resources.lib.Serie as Serie
				page_serie = Serie.GUI("vplay_serie.xml", __cwd__, "default", id = item.getProperty('id'))
			# =================================================================================================
			else:
				print 'Item : [%s]' % item.getLabel()
				print 'ID   : [%s]' % item.getProperty('id')
			# =================================================================================================
		elif controlId == 83:
			item = self.page_list.getSelectedItem()
			page_nr = item.getProperty('id')
			if not page_nr=='inactive':
				if not page_nr=='ppsel':
					self.page_number = page_nr
					if __test__:
						__htm__.getPage( url=__cwd__ + '\\samples\\search.htm', txdata=None )
					else:
						__htm__.getPage(url='http://www.vplay.ro/serials/?s=' + self.keyword + '&page=' + self.page_number, txdata=None)
					self.page = __htm__.Page
					self.RefreshItems()
					self.RefreshPages()
	
	def RefreshItems(self):
		items = re.compile('<a href="/serials/browse.do\?sid=(.+?)".+?><img src="(.+?)".+?/>(.+?)</a>').findall(self.page)
		self.list.reset()
		for id, img, title in items:
			title1 = title.split('/')[0].strip()
			if self.testmode=='true':
				img = ''
			item = xbmcgui.ListItem(title1, title1, img, img, '')
			item.setProperty('id', id)
			self.list.addItem(item)
	
	def RefreshPages(self):
		pages = re.compile('class="ppage(.+?)>(.+?)</a>').findall(self.page)
		self.page_list.reset()
		max_id = pages[len(pages)-1][0].replace('"','').strip().split('=')[1]
		for i in range(1, int(max_id) + 1):
			id = str(i)
			print 'Page [%s]' % id
			item = xbmcgui.ListItem(label=id)
			item.setProperty('id', id)
			if id==self.page_number:
				item.setInfo('video', {'trailer':'s'})
			else:
				item.setInfo('video', {'trailer':'n'})
			self.page_list.addItem(item)

		if (self.page_list.size()>0):
			self.getControl(81).setLabel(self.label + ' - pag. ' + self.page_number + ' :' )
			self.page_list.selectItem(int(self.page_number) - 1)
	
	def onAction(self, action):
		if action in self.action_cancel_dialog:
			self.close()

	def onFocus(self, controlId):
		pass
